package com.madou.dbtool.redis.init;

import com.madou.common.safe.utils.DecodeClassLoader;
import com.madou.common.safe.utils.DecodeClassLoaderUtil;
import com.madou.dbtool.common.enums.DBEnum;
import com.madou.dbtool.event.DBEventManager;
import com.madou.dbtool.event.def.event.OpenHtmlEvent;
import com.madou.dbtool.event.def.event.OpenReadmeEvent;
import com.madou.dbtool.node.RootNodeInitialization;
import com.madou.dbtool.redis.manager.RedisSourceManager;
import com.madou.dbtool.redis.manager.RedisSourceManagerFactory;
import com.madou.dbtool.ui.tree.DataSourceNode;
import com.madou.dbtool.utils.ConfigManager;
import com.madou.dbtool.utils.InputStreamUtils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * 初始化默认的Redis连接
 * @author miukoo
 */
public class RedisInit  implements RootNodeInitialization {
    boolean isRead = false;
    @Override
    public List<DataSourceNode> init() {
        ConfigManager.initConfigManager(getDBEnumType(), RedisInit.class);
        List<DataSourceNode> list = new ArrayList<>();
        HashMap defaultValue = new HashMap<>();
        defaultValue.put("name","localhost:6379");
        defaultValue.put("uri","localhost:6379");
        HashMap<String,Object> treeNode = (HashMap<String, Object>) ConfigManager.getInstance().getTreeNode(getDBEnumType(),defaultValue);
        DecodeClassLoader decodeClassLoader = DecodeClassLoaderUtil.getDecodeClassLoader();
        if(treeNode!=null&&treeNode.size()>0) {
            for (String serverId : treeNode.keySet()) {
                HashMap<String, String> servers = (HashMap<String, String>) treeNode.get(serverId);
                String value = servers.get("uri");
                String[] temp = value.split(":");
                if (temp.length > 1) {
                    String host = temp[0].trim();
                    int port = Integer.valueOf(temp[1].trim());
                    String password = null;
                    if (temp.length == 3) {
                        password = temp[2].trim();
                    }
                    addNode(serverId,servers.get("name"),decodeClassLoader, host, port, password, list);
                }
            }
        }
        if(treeNode==null||treeNode.size()==0) {
            addNode(UUID.randomUUID().toString(),"localhost:6379",decodeClassLoader,"localhost", 6379,null,list);
        }
        if(!isRead) {
            isRead = true;
            initReadMe();
        }
        return list;
    }

    @Override
    public DBEnum getDBEnumType() {
        return DBEnum.REDIS;
    }

    /**
     * 获取数据库连接
     * @param decodeClassLoader
     */
    public RedisSourceManager dataSourceManager(DecodeClassLoader decodeClassLoader,String host,int port,String password,String dataSourceName){
        try {
            Class<?> dataSourceManager = decodeClassLoader.findClassByAlias("directRedisSourceManager","com.madou.dbtool.redis.manager.DirectRedisSourceManager");
            RedisSourceManager o = (RedisSourceManager) dataSourceManager.getConstructors()[0].newInstance(host,port,password);
            RedisSourceManagerFactory.setDataSourceManager(dataSourceName,o);
            return o;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void addNode(String id,String dataSourceName,DecodeClassLoader decodeClassLoader, String host,int port,String password, List<DataSourceNode> list){
        try {
            Class<?> node = decodeClassLoader.findClassByAlias("redisDataSourceNode","com.madou.dbtool.redis.node.RedisDataSourceNode");
            RedisSourceManager directRedisSourceManager = dataSourceManager(decodeClassLoader,host,port,password,dataSourceName);
            final DataSourceNode o = (DataSourceNode) node.getConstructors()[0].newInstance(null, directRedisSourceManager,dataSourceName);
            o.setId(id);
            list.add(o);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化自述文件
     */
    private void initReadMe(){
        InputStream resourceAsStream = this.getClass().getResourceAsStream("/redis.html");
        if(resourceAsStream!=null){
            String temp = null;
            try {
                temp = InputStreamUtils.inputStreamTOString(resourceAsStream);
                DBEventManager.notice(new OpenHtmlEvent(temp, "使用帮助"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
